from django.urls import reverse
from django.views import View
from django.http import JsonResponse
from utils.searchViewModules import search_user, paginator_set, other_path, data_object_list  # 封装搜索和分页方法
import json
from django.db.models import Case, When, IntegerField, F
from django.db.models.functions import Random
from app.models import *
from app.url import *


class RecommendView(View):
    def post(self, request):
        try:
            # 获取所有用户列表并随机排序
            data = json.loads(request.body)
            search_params = {
                'page': int(data.get('page', 1)),  # 当前第几页
                'page_size': int(data.get('page_size', 10)),  # 一页多少条
                'nickname': data.get('nickname'),  # 名称搜索 接收字符串
                'age_range': data.get('age_range'),  # 年龄范围，格式为 'min_age-max_age'
                'height_range': data.get('height_range'),  # 身高范围，格式为 'min_height-max_height'
                'weight_range': data.get('weight_range'),  # 体重范围，格式为 'min_weight-max_weight'
                'marital_status': data.get('marital_status'),  # 婚姻状况 接收数组 ['未婚','离异']
                'ethnicity': data.get('ethnicity'),  # 民族 接收数组 ['汉族','回族']
                'children_status': data.get('children_status'),  # 子女情况 ['接收数组']
                'minimum_education': data.get('minimum_education'),  # 最低学历（多选条件） ['接收数组']
                'minimum_income': data.get('minimum_income'),  # 最低月收入 ['接收数组']
                'occupation': data.get('occupation'),  # 职业 ['接收数组']
                'housing_status': data.get('housing_status'),  # 住房情况 ['接收数组']
                'car_status': data.get('car_status'),  # 购车情况 ['接收数组']
                'marriage_timing': data.get('marriage_timing'),  # 期望结婚时间 ['接收数组']
                'work_province': data.get('work_province'),  # 工作地区 省 接收字符串
                'work_city': data.get('work_city'),  # 工作地区 市 接收字符串
                'work_area': data.get('work_area'),  # 工作地区 区 接收字符串
                'my_province': data.get('my_province'),  # 期望地区 省 接收字符串
                'my_city': data.get('my_city'),  # 期望地区 市 接收字符串
                'my_area': data.get('my_area'),  # 期望 地区 区 接收字符串
                'my_id': data.get('my_id'),  # 当前用户id
                'all_search': data.get('all_search')  # 当前用户id
            }
            # 获取用户列表并增加hot_status权重
            user_list = UserProfile.objects.annotate(
                adjusted_weight=Case(
                    When(stick_status=True, then=3),
                    default=1,
                    output_field=IntegerField(),
                ),
                hot_weight=Case(
                    When(hot_status=True, then=2),
                    default=1,
                    output_field=IntegerField(),
                ),
            ).order_by('-hot_weight', '-adjusted_weight', Random())

            full_url = request.path  # 获取当前请求地址
            recommend = reverse('recommend')  # 匹配我

            if full_url != recommend:
                if not search_params['my_id']:
                    return JsonResponse({
                        "code": "422",  # 错误状态码
                        "msg": "缺少重要参数:my_id",  # 错误消息
                    }, status=400)
                # 根据路由匹配不同情况
                user_list = other_path(user_list, full_url, search_params['my_id'])

            # 搜索
            user_list = search_user(user_list, search_params)

            # 排序并随机排列，确保hot_status为true的用户优先显示但不会全部集中在前面
            user_list = user_list.order_by(F('adjusted_weight').desc(), '?')
            # 进行分页

            paginated_data, paginator = paginator_set(user_list, search_params)

            # 将分页后的数据转换为字典列表
            data = data_object_list(paginated_data)

            # 返回分页后的数据
            return JsonResponse({
                "code": "200",  # 状态码
                "msg": "推荐搜索",  # 消息
                "data": data,  # 使用字典列表的数据
                "total": paginator.count,  # 总条目数
                "total_pages": paginator.num_pages,  # 总页数
                "current_page": paginated_data.number,  # 当前页数,
                "fileUrl": get_server_url(request)
            }, safe=False)
        except ValueError as e:
            # 捕获 UUID 格式错误并返回错误信息
            print(e)
            return JsonResponse({
                "code": "200",  # 错误状态码
                "msg": f"服务器错误: {e}",  # 错误消息
                "data": []  # 返回空数据
            }, status=200)


class InformationView(View):
    def get(self, request):
        try:
            my_id = request.GET.get('my_id', None)  # 获取用户id
            my_list = UserProfile.objects.get(id=my_id)  # 根据用户id查询字段
            data = {
                'id': my_list.id,
                'avatar': my_list.avatar,
                'gender': my_list.gender,
                'age': my_list.age,
                'nickname': my_list.nickname,
                'birthdate': my_list.birthdate,
                'marital_status': my_list.marital_status,
                'height': my_list.height,
                'weight': my_list.weight,
                'education': my_list.education,
                'monthly_income': my_list.monthly_income,
                'occupation': my_list.occupation,
                'housing_status': my_list.housing_status,
                'car_status': my_list.car_status,
                'marriage_expectation': my_list.marriage_expectation,
                'self_introduction': my_list.self_introduction,
                'parental_involvement': my_list.parental_involvement,
                'wechat': my_list.wechat,
                'wechat_QR': my_list.wechat_QR,
                'qq': my_list.qq,
                'parent_status': my_list.parent_status,
                'live_with_parents': my_list.live_with_parents,
                'smoking_status': my_list.smoking_status,
                'marriage_form': my_list.marriage_form,
                'children_status': my_list.children_status,
                'pets': my_list.pets,
                'hobbies': my_list.hobbies,
                'blood_type': my_list.blood_type,
                'ethnicity': my_list.ethnicity,
                'alma_mater': my_list.alma_mater,
                'employer_type': my_list.employer_type,
                'employer': my_list.employer,
                'property_location': my_list.property_location,
                'location': my_list.location,
                'age_range': my_list.age_range,
                'height_range': my_list.height_range,
                'minimum_education': my_list.minimum_education,
                'minimum_income': my_list.minimum_income,
                'marriage_timing': my_list.marriage_timing,
                'desired_housing_status': my_list.desired_housing_status,
                'desired_marital_status': my_list.desired_marital_status,
                'other_requirements': my_list.other_requirements,
                'realName': my_list.realName,
                'IDCode': my_list.IDCode,
                'diplomaImage': my_list.diplomaImage,
                'carImage': my_list.carImage,
                'houseImage': my_list.houseImage,
                'salaryImage': my_list.salaryImage,
                'work_time': my_list.work_time,
                'my_province': my_list.my_province,
                'my_city': my_list.my_city,
                'my_area': my_list.my_area,
                'work_province': my_list.work_province,
                'work_city': my_list.work_city,
                'work_area': my_list.work_area,
                'desired_work_province': my_list.desired_work_province,
                'desired_work_city': my_list.desired_work_city,
                'desired_work_area': my_list.desired_work_area,
                'stick_status': my_list.stick_status,
                'hot_status': my_list.hot_status
            }
            return JsonResponse({
                "code": "200",  # 状态码
                "msg": "推荐搜索",  # 消息
                "my_list": data,  # 用户信息
                "fileUrl": get_server_url(request)
            }, safe=False)
        except Exception as e:
            return JsonResponse({
                "code": 200,
                "msg": "查询不到" + str(e),
            })
